package com.cqndt.visual.util;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * Created By marc
 * Date: 2021/5/25  14:04
 * Description:
 */
public class FileViewUtil {

    public static void readByIo(String attachmentUrl,HttpServletResponse response){
        // 获取文件的后缀名
        String suffixName = attachmentUrl.substring(attachmentUrl.lastIndexOf("."));
        try{
            if(suffixName.equalsIgnoreCase(".jpg")||suffixName.equalsIgnoreCase(".png")
                    ||suffixName.equalsIgnoreCase(".gif")||suffixName.equalsIgnoreCase(".tif")
                    ||suffixName.equalsIgnoreCase(".jpeg")||suffixName.equalsIgnoreCase(".svg")
                    ||suffixName.equalsIgnoreCase(".bmp")||suffixName.equalsIgnoreCase(".webp")){
                readImgByIO(attachmentUrl,response,"image/*;charset=utf-8");
            }else if(suffixName.equalsIgnoreCase(".mp4")||suffixName.equalsIgnoreCase(".avi")
                    ||suffixName.equalsIgnoreCase(".rmvb")||suffixName.equalsIgnoreCase(".mkv")
                    ||suffixName.equalsIgnoreCase(".ogg")
                    ||suffixName.equalsIgnoreCase(".flv")
                    ||suffixName.equalsIgnoreCase(".wmv")){
                readImgByIO(attachmentUrl,response,"video/mpeg4;charset=utf-8");
            }else{
                response.sendError(500,"文件不可预览");
            }
        }catch (IOException e) {
            try {
                response.sendError(500,"服务器内部错误");
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }
    /**
     * 流的形式输出
     */
    private static void readImgByIO(String filePath,HttpServletResponse response,String contentType) throws IOException {
        File filePic = new File(filePath);
        if(filePic.exists()){
            ServletOutputStream out = null;
            FileInputStream ips = null;
            try{
                ips = new FileInputStream(filePic);
                int i = ips.available(); // 得到文件大小
                byte data[] = new byte[i];
                ips.read(data); // 读数据
                response.setContentType(contentType); // 设置返回的文件类型
                out = response.getOutputStream(); // 得到向客户端输出二进制数据的对象
                out.write(data); // 输出数据
                out.flush();
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                out.close();
                ips.close();
            }
        }
    }
}
